﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.Linq;
using System.Threading;

namespace System
{
    /// <summary>
    /// Summary description for DataContextFactory
    /// </summary>
    public class DataContextFactory
    {
        public DataContextFactory()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        /// <summary>   
        /// Creates a ASP.NET Context scoped instance of a DataContext. This static 
        /// method creates a single instance and reuses it whenever this method is  
        /// called.    
        /// This version creates an internal request specific key shared key that is
        /// shared by each caller of this method from the current Web request.    
        /// </summary>
        public static TDataContext GetWebRequestScopedDataContext<TDataContext>() where TDataContext : DataContext, new()
        {
            // *** Create a request specific unique key     
            return (TDataContext)GetWebRequestScopedDataContextInternal(typeof(TDataContext), null, null);
        }
        /// <summary> 
        /// Internal method that handles creating a context that is scoped to the HttpContext Items collection 
        /// by creating and holding the DataContext there. 
        /// </summary>   
        /// <param name="type"></param>   
        /// <param name="key"></param>   
        /// <param name="connectionString"></param>
        /// <returns></returns>  
        static object GetWebRequestScopedDataContextInternal(Type type, string key, string connectionString)
        {
            object context;
            if (HttpContext.Current == null)
            {
                if (connectionString == null)
                    context = Activator.CreateInstance(type);
                else
                    context = Activator.CreateInstance(type, connectionString);
                return context;
            }
            // *** Create a unique Key for the Web Request/Context   
            if (key == null)
                key = "__WRSCDC_" + HttpContext.Current.GetHashCode().ToString("x") + Thread.CurrentContext.ContextID.ToString();
            context = HttpContext.Current.Items[key];
            if (context == null)
            {
                if (connectionString == null)
                    context = Activator.CreateInstance(type);
                else
                    context = Activator.CreateInstance(type, connectionString);
                if (context != null)
                    HttpContext.Current.Items[key] = context;
            }
            return context;
        }
    }
}